<?php

namespace App\Admin\Controllers\User;

use App\Models;
use App\Models\Province;
use App\Models\User\User;
use App\Models\School;
use App\Models\School\Classes;
use App\Models\School\Teacher;
use App\Models\Sys;
use App\Models\Sys\Exchange;
use App\Models\Subscribe;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Row;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Column;

use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;

use Encore\Admin\Widgets;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Widgets\Table;
use Encore\Admin\Widgets\Collapse;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use App\Admin\Extensions\Tools;


class UserController extends Controller
{
    use ModelForm;
    protected $header = '用户列表';

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header($this->header);
            $content->description('description');

            $content->body($this->grid());
        });
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('用户详情')
            ->description('Detail')
            ->body($this->detail($id,$content));
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header($this->header);
            $content->description('description');

            $content->row(view('admin.user.tab',['user_id'=>$id]));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    /*public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header($this->header);
            $content->description('description');

            $content->body($this->form());
        });
    }*/

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(User::class, function (Grid $grid) {

            $grid->model()->select([
                'id',
                'username',
                'telephone',
                'role_id',
                'initial_role_id',
                'nickname',
                'created_at',
                'gender',
                'reg_from',
            ])->orderBy('id','DESC');

            $grid->id('用户ID')->sortable();

            $grid->telephone('手机号');
            $grid->column('手机号归属地')->display(function (){
                $col = '';
                if ($this->telephone && is_mobile($this->telephone)) {
                    $url = "http://mobsec-dianhua.baidu.com/dianhua_api/open/location?tel=" . $this->telephone;
                    $res = json_decode(curl($url), true);
                    if ($res['response'] && $res['response'][$this->telephone]) {
                        $col = $res['response'][$this->telephone]['location'];
                    }
                }

                return $col;
            });

            $grid->username('用户昵称');
            $grid->initial_role_id('初始身份')->using([
                '1'=>'老师',
                '2'=>'家长',
            ]);


            /*$grid->vip('会员级别')->display(function ($vip){
                if ($vip){
                    $vip = pos($vip);
                    return $vip['name'];
                } else {
                    return '无';
                }
            });*/

            $grid->vip('会员级别')->display(function ($val){
                $return = '';
                foreach ($val as $k=>$v){
                    $return .= '<span class="label label-success">'.$v['name'].'</span> ';
                }
                return $return;
            });

            //$grid->role_id('订阅状态');
            $grid->account()->money('可用校币');
            $grid->account()->expe('经验值');
            /*$grid->role_id('登录状态')->using([
                '1'=>'老师',
                '2'=>'家长',
            ]);*/

            $grid->role_id('身份')->display(function ($v){
                if ($v == 1){
                    return '<span style="color:green;">老师</span>';
                } else {
                    return '<span style="color:red;">家长</span>';
                }
            });

            $grid->reg_from('注册来源');

            $grid->column('学校信息')->display(function (){
                $result = User::school($this->id, $this->role_id);

                $column = '';
                if ($result) {
                    foreach ($result as $key=>$val) {
                        $school_name = $val->school_name ? $val->school_name : ($val->s_name ? $val->s_name : $val->name);
                        $city = "$val->province $val->city $val->district $val->address ";
                        $column .= "$school_name  $city" . "<br>";
                    }
                }

                return $column;
            });

            $grid->created_at('创建时间');

            //搜索栏
            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();

                $filter->column(1/3, function ($filter) {
                    $filter->like('telephone','手机号');
                    $filter->equal('role_id', '身份')
                        ->select([
                            '1'=>'老师',
                            '2'=>'家长'
                        ]);
                    $filter->equal('reg_from', '注册来源')
                        ->select(User::$reg_from_map);

                    /*$filter->where(function ($query) {

                        $input = $this->input;
                        //$query->where('jxt_xp_user.role_id', $input);

                        $query->whereHas('tags', function ($query) use ($input) {
                            $query->where('name', $input);
                        });

                    }, '身份', 'role_id')->select([
                        '1'=>'老师',
                        '2'=>'家长'
                    ]);*/
                });

                $filter->column(1/3, function ($filter) {
                    $filter->like('username','用户名');
                    $filter->between('created_at', '创建时间')->datetime();
                });




            });

            $grid->disableCreateButton();

            /*$grid->tools(function ($tools) {
                $url = "/admin/artimage";
                $icon = "fa-backward";
                $text = "Back";
                $tools->append(new Tools\ShowArtwork($url,$icon,$text));
            });*/

        });

    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(User::class, function (Form $form) {

            $form->display('id', '用户id');
            $form->display('telephone', '手机号码');

            //$form->multipleSelect('vip', '会员级别')->options(Models\Member\Price::options());
            $form->select('member.vip_id', '会员级别')->options(Models\Member\Price::options());

            $form->radio('gender', '性别')
                ->options(['0'=>'保密','1' => '男', '2'=> '女']);

            $form->date('birthday', '生日');

            $form->select('province_id','省')->options(
                Models\City::province()->pluck('name', 'id')
            )->load('city_id', '/api/city/city');

            $form->select('city_id','市')->options(function ($city_id) {
                return Models\City::options($city_id);
            })->load('area_id', '/api/city/area');

            $form->select('area_id', '区')->options(function ($area_id) {
                return Models\City::options($area_id);
            });

            //$form->text('','职业');
            $form->textarea('note', '备注');

            /*$form->password('password', '密码');
            $form->password('password_confirmation', '确认密码');*/
            $form->switch('status','账户启用状态')->states([
                'on'  => ['value' => 1, 'text' => '是', 'color' => 'success'],
                'off' => ['value' => 9, 'text' => '否', 'color' => 'danger'],
            ]);

            $form->disableEditingCheck();
            $form->disableViewCheck();
            $form->disableReset();

            $form->tools(function (Form\Tools $tools){
                $tools->disableList();
            });

            $form->ignore(['password_confirmation']);

            $form->saving(function (Form $form) {

                if ($form->password) {
                    if ($form->password != $_REQUEST['password_confirmation']) {
                        $error = new MessageBag([
                            'title'   => '失败...',
                            'message' => '两次密码不一致....',
                        ]);

                        return back()->with(compact('error'));
                    } else {

                        $salt = substr(md5(uniqid()), 6, 6);
                        $password = \AES::encrypt($form->password, $salt);
                        //$password2 = \AES::decrypt($password, $salt);
                        //dd(compact('password', 'password2'));

                        $form->salt = $salt;
                        $form->password = $password;
                    }
                }

//                $vip_id = ($form->member)['vip_id'];
//
//                if ($vip_id) {
//                    if ($form->model()->member) {
//                        if ($form->model()->member->vip_id != $vip_id) {
//                            $vip_price = Models\Member\Price::where('id', $vip_id)->select(['id', 'term'])->first();
//                            if ($vip_price) {
//                                $form->model()->member->create_at = time();
//                                $form->model()->member->start_time = time();
//                                $form->model()->member->expiry_time = strtotime('+' . $vip_price->term . ' month', time());
//                            }
//                        }
//                    } else {
//
//                        $vip_price = Models\Member\Price::where('id', $vip_id)->select(['id', 'term'])->first();
//                        if ($vip_price) {
//                            $member = new Models\Member\User();
//                            $member->user_id = $form->model()->id;
//                            $member->vip_id = $vip_id;
//                            $member->create_at = time();
//                            $member->start_time = time();
//                            $member->expiry_time = strtotime('+' . $vip_price->term . ' month', time());
//                            $member->save();
//                        }
//                    }
//
//                }


            });

            //$form->number('数字');
            /*$form->divider('divider');
            $form->decimal('decimal');
            $form->currency('currency');*/

            //$form->setAction('/users/editUser');

            /*$form->submitted(function (Form $form) {
                echo 1;die;
            });

            $form->saving(function (Form $form) {

                $success = new MessageBag([
                    'title'   => 'title...',
                    'message' => 'message....',
                ]);

                return back()->with(compact('success'));
            });*/

        });
    }

    protected function showFormParameters($content)
    {
        $parameters = request()->except(['_pjax', '_token']);

        if (!empty($parameters)) {

            ob_start();

            dump($parameters);

            $contents = ob_get_contents();

            ob_end_clean();

            $content->row(new Box('Form parameters', $contents));
        }
    }

    protected function detail($id,Content $content)
    {

        //基本资料 会员信息
        $user_data = User::with('vip')
            ->with('address')
            ->findOrFail($id,['id','telephone','nickname','gender','avatar','birthday','province_id','city_id','area_id','created_at','reg_from']);

        //班级信息 创建班级数
        $classes_data = Classes::where('create_by',$id)
            ->with('school')
            ->get()->toArray();

        $ids = array_column($classes_data,'class_id');

        $subscribe = new Subscribe\Info();
        $subscribe_count_data = $subscribe->select(DB::raw('count(*) as subscribe_count, class_id'))
            ->whereIn('class_id', $ids)
            ->groupBy('class_id')
            ->get()->toArray();
        $subscribe_count_data = array_column($subscribe_count_data, null, 'class_id');

        $student = new School\Student();
        $student_count_data = $student->select(DB::raw('count(*) as student_count, class_id'))
            ->whereIn('class_id', $ids)
            ->groupBy('class_id')
            ->get()->toArray();
        $student_count_data = array_column($student_count_data, null, 'class_id');

        foreach($classes_data as $key=>$val){
            $classes_data[$key]['subscribe_count'] = $subscribe_count_data[$val['class_id']]['subscribe_count'] ?? 0;
            $classes_data[$key]['student_count'] = $student_count_data[$val['class_id']]['student_count'] ?? 0;
        }

        //加入班级数
        $classes_count = Teacher::where('user_id',$id)->count();

        $user_data = $user_data->toArray();

        switch ($user_data['gender']){
            case '1':
                $user_data['gender'] = '男';
                break;
            case '2':
                $user_data['gender'] = '女';
                break;
            default:
                $user_data['gender'] = '保密';
        }

        if ($user_data['vip']){
            $user_data['vip'] = pos($user_data['vip']);
        }

        $area = [];
        if ($user_data['province_id']){
            $area[] = $user_data['province_id'];
        }
        if ($user_data['city_id']){
            $area[] = $user_data['city_id'];
        }
        if ($user_data['area_id']){
            $area[] = $user_data['area_id'];
        }
        if ($area){
            $province_data = Province::findOrFail($area,['name'])->toArray();
            $area = implode(' ', array_column($province_data,'name'));
        } else {
            $area= '--';
        }

        $user_data['area'] = $area;

        $user_data['create_count'] = count($classes_data);
        $user_data['classes_count'] = $classes_count;

        $school_count = count(array_unique(array_column($classes_data,'school_code')));
        $user_data['school_count'] = $school_count;

        $content->row(view('admin.user.show',$user_data));
        $content->row(new Box('班级信息', view('admin.user.classes',['data'=>$classes_data])));
        $content->row(new Box('收货地址', view('admin.user.address',['data'=>$user_data['address']])));

        $grid = new Grid(new Exchange());
        $grid->disableFilter();
        $grid->disableExport();
        $grid->disableActions();
        $grid->disableRowSelector();
        $grid->disableCreateButton();
        //$grid->disableRefresh();
        $grid->model()->where('user_id',$id);
        $grid->id('id');
        $grid->order_sn('订单编号');
        $grid->create_at('提交时间');
        $grid->money('所需校币');
        $grid->status('订单状态')->using([
            '1'=>'兑换',
            '9'=>'取消'
        ]);
        $grid->column('操作')->display(function (){
            return '<a href="/exchange/'.$this->id.'">查看订单</a>';
        });

        $content->row(new Box('兑换记录',$grid->render()));

    }

    public function parentDetail($id, Content $content)
    {
        $child_data = DB::table('jxt_sys_child as a')
            ->leftJoin('jxt_school_child_student as b', 'b.child_id', 'a.child_id')
            ->leftJoin('jxt_school_student as c', 'c.student_id', 'b.student_id')
            ->leftJoin('jxt_school_classes as d', 'd.class_id', 'c.class_id')
            ->leftJoin('jxt_sys_school as e', 'e.id', 'd.school_code')
            ->leftJoin('jxt_xp_user as f', 'f.id', 'd.create_by')
            ->leftJoin('jxt_subscribe_info_list as g', [
                ['g.user_id','a.create_by'],
                ['g.child_id','a.child_id'],
                ['g.class_id','d.class_id']
            ])
            ->where([
                ['a.create_by',$id],
                ['a.status','1'],
                ['b.status','1'],
                ['c.status','1'],
                ['d.status','1']
            ])
            ->select([
                'a.child_id','a.name_home','a.create_by as user_id',
                'c.student_id','c.name_class',
                'd.class_id','d.create_by','d.name', 'd.school_name',
                'e.id as school_id','e.school_name as sch_name',
                'f.username',
                'g.id as subscribe_id','g.subscribe_time','g.end_time','g.status as subscribe_status'
            ])
            ->get();

        foreach ($child_data as $key=>$val){
            if (isset($val->subscribe_time) && isset($val->end_time)){
                if ($val->end_time < time()){
                    $val->subscribe_time = '';
                    $val->end_time = '';
                    $child_data[$key]->disabled = 1;
                }else{
                    if ($val->subscribe_time < time()){
                        $child_data[$key]->disabled = 1;
                    }
                    $val->subscribe_time = date('Y-m-d H:i:s', $val->subscribe_time);
                    $val->end_time = date('Y-m-d H:i:s', $val->end_time);
                }
            } else {
                $val->subscribe_time = '';
                $val->end_time = '';
                $child_data[$key]->disabled = 1;
            }
        }

        return $content
            ->header('家长身份')
            ->description('Detail')
            ->body(view('admin.user.parent',['data'=>$child_data,'user_id'=>$id]));
    }

    /**
     * 家长身份--删除孩子
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delChild(Request $request)
    {
        $flag = false;
        try {
            $id = $request->input('id');
            if ($id){

                $child = Sys\Child::find($id);

                if ($child){
                    $child->status = 9;
                    if ($child->save()){
                        $flag = true;
                    }
                }
            }
        } catch (\Exception $e) {
            $msg = $e->getMessage();
        }

        if ($flag){
            return response()->json([
                'status'  => true,
                'message' => trans('admin.delete_succeeded'),
            ]);
        } else {
            return response()->json([
                'status'  => false,
                'message' => $msg ?? '删除失败',
            ]);
        }
    }

    /**
     * 家长身份--调整孩子订阅时间
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateChild(Request $request)
    {
        $user_id      = $request->input('user_id');
        $child_id     = $request->input('child_id');
        $class_id     = $request->input('class_id');
        $subscribe_id = $request->input('subscribe_id');
        $start_time   = $request->input('start_time');
        $end_time     = $request->input('end_time');

        if (!$start_time || !$end_time){
            return response()->json([
                'status'  => false,
                'message' => '参数错误',
            ]);
        }

        $flag = false;

        //是否订阅过
        if ($subscribe_id){

            $info = Subscribe\Info::find($subscribe_id);

            if ($info){

                $start_time = strtotime($start_time);
                $end_time = strtotime($end_time);

                //判断是否到期
                if ($info->end_time < time()){
                    if ($start_time < $end_time && $end_time > time()){
                        $info->subscribe_time = $start_time;
                        $info->end_time = $end_time;
                        $info->status = 1;
                        $flag = true;
                    } else {
                        $msg = '到期时间必须大于订阅时间';
                    }
                } else {
                    if ($info->end_time < $end_time) {
                        $info->end_time = $end_time;

                        $flag = true;
                    } else {
                        $msg = '调整到期时间必须大于当前到期时间';
                    }
                }

                //订阅
                if ($flag){
                    try {
                        $info->is_manual = 1;
                        $flag = $info->save();
                    } catch (\Exception $e) {
                        $flag = false;
                        $msg = $e->getMessage();
                    }
                }


            } else {
                $msg = '数据异常';
            }

        } else {

            /*$count = Subscribe\Info::where([
                ['child_id'=>$child_id],
                ['class_id'=>$class_id],
                ['user_id'=>$user_id],
            ])->count();*/

            $count = Subscribe\Info::where('child_id', $child_id)->where('class_id', $class_id)->where('user_id', $user_id)->count();

            if (!$count){
                if ($start_time < $end_time) {

                    $info = new Subscribe\Info();
                    $info->child_id = $child_id;
                    $info->class_id = $class_id;
                    $info->user_id = $user_id;
                    $info->subscribe_time = time();
                    $end_time = strtotime($end_time);
                    $info->end_time = $end_time;
                    $info->remind = $end_time - (7 * 86400);
                    $info->subscribe_id = 0;
                    $info->is_manual = 1;

                    $flag = $info->save();

                } else {
                    $msg = '到期时间必须大于订阅时间';
                }
            }
        }

        if ($flag){
            $msg = trans('admin.update_succeeded');
        } else {
            $msg = $msg ?? trans('admin.update_succeeded');
        }

        return response()->json([
            'status'  => $flag,
            'message' => $msg,
        ]);

    }

    /**
     * 编辑用户资料
     *
     * @param $id
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update111($id, Request $request)
    {
        $flag = true;
        $user = User::find($id);
        if ($user){
            $vip                   = $request->input('vip');
            $gender                = $request->input('gender');
            $birthday              = $request->input('birthday');
            $province_id           = $request->input('province_id');
            $city_id               = $request->input('city_id');
            $area_id               = $request->input('area_id');
            $note                  = $request->input('note');
            $password              = $request->input('password');
            $password_confirmation = $request->input('password_confirmation');
            $status                = $request->input('status');

            $status = $status == 'on' ? '1' : '9';

            if (!in_array($gender,['1','2'])){
                $gender = '0';
            }

            $user->gender      = $gender;
            $user->birthday    = strtotime($birthday);
            $user->province_id = $province_id;
            $user->city_id     = $city_id;
            $user->area_id     = $area_id;
            $user->note        = $note;
            $user->status      = $status;

            if ($password){
                if (isset($password_confirmation)){
                    if ($password == $password_confirmation){
                        $user->password = $password;
                    }else{
                        $flag = false;
                        $msg  = '两次密码不一致';
                    }
                }else{
                    $flag = false;
                    $msg  = '请输入确认密码';
                }
            }

            if ($flag)
            $flag = $user->save();


        }else{
            $flag = false;
            $msg  = '用户不存在';
        }

        if ($flag){
            //return admin_success('111111', '2222222222222');
            admin_toastr(trans('admin.update_succeeded'), 'success');
            /*$success = new MessageBag([
                'title'   => 'title...',
                'message' => 'message....',
            ]);
            return back()->with(compact('success'));*/

        } else {
            $error = new MessageBag([
                'title'   => trans('admin.update_failed'),
                'message' => $msg ?? '',
            ]);

            return back()->with(compact('error'));
        }




    }





}
